﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using LdExpress;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    public string strCondition = "";
    public string strError = "";
    public string strMess = "";
    public int nPermissions = 0;
    public int ctrrow = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["ActiveCust"] != null && int.Parse(Session["ActiveCust"].ToString()) > 0)
        {
            if (Session["ActiveCust"] != "") nPermissions = int.Parse(Session["ActiveCust"].ToString());
            if (Session["superadmin"] != "" && int.Parse(Session["superadmin"].ToString()) >= 7) nPermissions = 10;
        }
        if (nPermissions < 7)
            Response.Redirect("Login.aspx");
        if (!IsPostBack)
        {
        }
    }
    protected void SubmitImport_Click(object sender, System.EventArgs e)
    {
        CustomerActive obj = null;
        HttpPostedFile inpFile = null;
        FileInfo FICSV = null;
        DataColumnCollection tableColumns = null;
        bool isExcludeSum = false;
        if (cbExcludedSummary.Checked) isExcludeSum = true;
        string fileName = Request.Form["txtfileUpLoad"];

        if (Request.Files["txtfileUpLoad"] != null)
        {
            inpFile = Request.Files["txtfileUpLoad"];
        }
        if (txtfileUpLoad.PostedFile.FileName != "")
        {
            FICSV = new FileInfo(txtfileUpLoad.PostedFile.FileName);
            try
            {
                ImportDB.SaveFileToServer(fileName, inpFile);

                DataSet dsCSV = new DataSet();
                dsCSV = ImportDB.ConnectFile(FICSV);

                try
                {
                    tableColumns = dsCSV.Tables[0].Columns;
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                DataRowCollection tableRows = dsCSV.Tables[0].Rows;
                long curUserID = -1;
                long curOwnerID = -1;
                int totalRows = 0;
                int addRows = 0;
                int updateRows = 0;
                try
                {
                    curUserID = long.Parse(Session["logined_id"].ToString());
                    curOwnerID = long.Parse(Session["logined_id"].ToString());
                }
                catch { curUserID = -1; }
                GV.Response.Clear();
                GV.Response.Write("<div id='divCurrentRow' style='margin: auto;width: 500px;font-size: 20px;font-weight: bold;color: red;'>");
                GV.Response.Write("Importing Current Row: <span id='spanCurrentRow'></span></div>");
                GV.Response.Flush();
                foreach (DataRow row in tableRows)
                {
                    obj = new CustomerActive();
                    object[] rowItems = row.ItemArray;

                    int ctrColumn = 0;
                    if (rowItems[3].ToString().Replace("'", "").Trim().Length > 0)
                    {
                        ctrrow++;
                        //Check to Sum vol
                        double nCont20 = 0, nCont40 = 0;
                        int nVolsExt = 0;
                        double dTemp;
                        int iTemp;
                        obj.Code = rowItems[2].ToString().Replace("'", "").Trim();
                        if (obj.Code.Length == 9 || obj.Code.Length == 12) obj.Code = "0" + obj.Code;
                        obj.Active_Type = CommonFunctions.GetActiveTypeByCodeType(rowItems[11].ToString());
                        try
                        {
                            obj.LastUpdate = DateTime.Parse(rowItems[0].ToString().Trim());
                        }
                        catch { }
                        string strHsGoods = rowItems[4].ToString();
                        string strHsGoodsEx = rowItems[5].ToString();
                        if (strHsGoods.Length > 4)
                            strHsGoods = strHsGoods.Substring(0, 4);
                        if (strHsGoodsEx.Length > 4)
                            strHsGoodsEx = strHsGoodsEx.Substring(0, 4);
                        long tempID = CustomerActive.GetCustIDToImportActiveCust(obj.Code, rowItems[1].ToString(), rowItems[8].ToString()
                            , strHsGoods, strHsGoodsEx
                            , obj.LastUpdate, obj.Active_Type, rowItems[12].ToString(), rowItems[14].ToString()
                            , out nCont20, out nCont40, out nVolsExt, GV.cn, GV.trans);
                        if (tempID > 0) // sum vol cont 20, 40 when the same pol, pld, code
                        {
                            if (isExcludeSum) continue;
                            obj.ID = tempID;
                            obj.Load(GV.cn, GV.trans);

                            double.TryParse(rowItems[6].ToString().Replace("'", "").Replace(",", ".").Trim(), out dTemp);
                            dTemp += nCont20;
                            obj.Vols = System.Math.Round(dTemp).ToString();
                            double.TryParse(rowItems[7].ToString().Replace("'", "").Replace(",", ".").Trim(), out dTemp);
                            dTemp += nCont40;
                            obj.Report = System.Math.Round(dTemp).ToString();
                            obj.Address = CommonFunctions.GetProvinceByTaxCode(obj.Code);
                            updateRows++;
                        }
                        else
                        {
                            obj.Pol = rowItems[1].ToString().Replace("'", "").Trim();
                            obj.Name = rowItems[3].ToString().Replace("'", "").Trim();
                            obj.Address = CommonFunctions.GetProvinceByTaxCode(obj.Code);
                            obj.HsGoods = strHsGoods;
                            obj.HsGoodsEx = strHsGoodsEx;

                            double.TryParse(rowItems[6].ToString().Replace("'", "").Replace(",", ".").Trim(), out dTemp);
                            obj.Vols = System.Math.Round(dTemp).ToString();
                            double.TryParse(rowItems[7].ToString().Replace("'", "").Replace(",", ".").Trim(), out dTemp);
                            obj.Report = System.Math.Round(dTemp).ToString();
                            obj.Routers = rowItems[8].ToString().Replace("'", "").Trim();
                            obj.Goods = rowItems[9].ToString().Replace("'", "").Trim();
                            obj.GoodsEx = rowItems[10].ToString().Replace("'", "").Trim();
                            obj.Active_Dlvry = rowItems[12].ToString();
                            obj.ProvinceID = Tinh.GetIDFromCode(obj.Code.Substring(0, 2), GV.cn, GV.trans);
                            try
                            {
                                obj.Active_Value = float.Parse(rowItems[13].ToString());
                            }
                            catch { }
                            obj.Active_Cnee = rowItems[14].ToString();
                            addRows++;
                        }
                        Countries objCountry = new Countries();
                        string inputCountryCode = rowItems[15].ToString().Replace("'", "").Trim();
                        if (inputCountryCode.Length >= 2)
                        {
                            objCountry.Load(inputCountryCode.Substring(0, 2), GV.cn, GV.trans);
                            obj.Country = objCountry.CountryName;
                            if (objCountry.CountryName.Length == 0)
                                obj.Country = inputCountryCode;
                        }
                        else
                            obj.Country = inputCountryCode;
                        obj.Archive = 2;
                        obj.UserID = curUserID;
                        obj.Owner = curOwnerID;
                        //Check Duplicate
                        long crmID = 0;
                        if (obj.Code.Length > 0)
                            crmID = CustomerRelation.IsCodeExisting(obj.Code, GV.cn, GV.trans);
                        else
                            crmID = CustomerRelation.IsUniqueNameExisting(obj.Name, GV.cn, GV.trans);
                        if (crmID > 0)
                        {
                            obj.Duplicate = 1;
                        }
                        ctrColumn++;
                        obj.Save(GV.cn, GV.trans);
                        totalRows++;
                        GV.Response.Clear();
                        GV.Response.Write("<script> window.document.getElementById('spanCurrentRow').innerHTML='" + ctrrow + "';</script>");
                        GV.Response.Flush();
                    }
                }
                strMess = "Total: " + totalRows + " records:<br>";
                if (addRows > 0)
                    strMess += "  - Added New: " + addRows.ToString() + " records.<br>";
                if (updateRows > 0)
                    strMess += "  - Updated: " + updateRows.ToString() + " records.";
                GV.Response.Clear();
                GV.Response.Write("<script> window.document.getElementById('divCurrentRow').innerHTML='DONE!';</script>");
                GV.Response.Flush();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());

            }
        }
        else
        {
            strMess = "Bạn phải chọn file import!";
            return;
        }
    }
}

